package com.mashibing.jvm.c3_jmm.cacheling;

/**
 * 该引用保证两个对象在不同的缓存行，
 * 运行结构比前一个快5倍
 * 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 5, 6, 5, 6, 5,
 */
public class T02_CacheLinePadding {
    private static class Padding{
        public volatile long p1,p2,p3,p4,p5,p6,p7;
    }

    private static class T extends Padding{
        public volatile long x;
        // public volatile long p8,p9,p10,p11,p12,p13,p14; // 这个放开注释更能确保不同的cpu读取的是不同的缓存行
    }

    public static T[] arr  = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void testMethod() throws InterruptedException {

        final long len = 1000_0000L;
        Thread t1 = new Thread(()->{
            for (long i = 0; i < len; i++) {
                arr[0].x = i;
            }
        });

        Thread t2 = new Thread(()->{
            for (long i = 0; i < len; i++) {
                arr[1].x = i;
            }
        });

        final long start = System.nanoTime();
        t1.start();t2.start();
        t1.join();t2.join();

        System.out.print((System.nanoTime()-start)/len + ", ");

    }

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 20; i++) {
            testMethod();
        }
    }
}
